package com.mocoop.commom;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.util.Log;

public class PhotoUtils {

	// public static void imageZoom(Bitmap bitmap) {
	// //图片允许最大空间 单位：KB
	// double maxSize = 200.00;
	// //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	// byte[] b = baos.toByteArray();
	// //将字节换成KB
	// double mid = b.length/1024;
	// //判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
	// if (mid > maxSize) {
	// //获取bitmap大小 是允许最大大小的多少倍
	// double i = mid / maxSize;
	// //开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
	// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
	// bitmap = zoomImage(bitmap, bitmap.getWidth() / Math.sqrt(i),
	// bitmap.getHeight() / Math.sqrt(i));
	// }
	// }

	public static void saveBitmapToFile(String fileName, Bitmap bitmap) {
		try {
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(fileName)));
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	 private static int computeInitialSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
	        // Raw height and width of image
	        final double height = options.outHeight;
	        final double width = options.outWidth;

	        final long maxNumOfPixels = reqWidth * reqHeight;
	        final int minSideLength = Math.min(reqHeight, reqWidth);

	        int lowerBound = (maxNumOfPixels < 0) ? 1 :
	                (int) Math.ceil(Math.sqrt(width * height / maxNumOfPixels));
	        int upperBound = (minSideLength < 0) ? 128 :
	                (int) Math.min(Math.floor(width / minSideLength),
	                        Math.floor(height / minSideLength));

	        if (upperBound < lowerBound) {
	            // return the larger one when there is no overlapping zone.
	            return lowerBound;
	        }

	        if (maxNumOfPixels < 0 && minSideLength < 0) {
	            return 1;
	        } else if (minSideLength < 0) {
	            return lowerBound;
	        } else {
	            return upperBound;
	        }
	    }


	public static Bitmap decodeOriginImage(String imageFile,int dWidth,int dHeight) {
		Bitmap bmp = null;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		bmp = BitmapFactory.decodeFile(imageFile, opts);

		opts.inSampleSize = computeSampleSize(opts, dHeight, dHeight);
		opts.inJustDecodeBounds = false;
		
		try {
			bmp = BitmapFactory.decodeFile(imageFile, opts);
		} catch (OutOfMemoryError err) {
		}
		return bmp;
	}

	@SuppressLint("NewApi")
	public static Bitmap decodeImage(String photoPath, int maxWidth, int maxHeight) {
		if (photoPath.indexOf("file") == 0) {
			photoPath = photoPath.substring(7);
		}
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(photoPath, bmOptions);
		File file = new File(photoPath);
		if (!file.exists()) {
			return null;
		}

		

		// int inSampleSize = BitmapUtils.calculateInSampleSize(bmOptions,
		// maxWidth, maxHeight);
		int inSampleSize = 1;
		if (bmOptions.outHeight > maxHeight || bmOptions.outWidth > maxWidth) {
			inSampleSize = (int) Math.pow(2, (int) Math.round(Math.log(maxHeight / (double) Math.max(bmOptions.outHeight, bmOptions.outWidth)) / Math.log(0.5)));
		}

		bmOptions.inSampleSize = inSampleSize;
		bmOptions.inPurgeable = true;
		bmOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
		bmOptions.inInputShareable = true;
		bmOptions.inJustDecodeBounds = false;

		Bitmap bitmap = BitmapFactory.decodeFile(photoPath, bmOptions);
		if (bitmap == null) {
			return null;
		}
		Log.i("PhotoUtils", "width = " + bitmap.getWidth() + ", height = " + bitmap.getHeight());

		if (inSampleSize > 1) {
			Matrix m = new Matrix();
			RectF inRect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
			RectF outRect = new RectF(0, 0, maxWidth, maxHeight);
			m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
			float[] values = new float[9];
			m.getValues(values);

			// resize bitmap
			Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * values[0]), (int) (bitmap.getHeight() * values[4]), true);
			return resizedBitmap;
		} else {
			return bitmap;
		}

	}

	public static int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信息
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图片
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
		} catch (OutOfMemoryError e) {
		}
		if (returnBm == null) {
			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;
	}
}
